#include "HMC5883.H"
#include <stdio.h>
#include <string.h>
#include <stdint.h>
/*需要配置的寄存器：1.测量模式 2.测量ID验证*/
void HMC5883_Init(I2C_HandleTypeDef *hi2c)
{
    uint8_t id[3] = {0, 0, 0}; // 存储读取的ID
    HAL_I2C_Mem_Read(hi2c, HMC5883_ADDRESS << 1, HMC5883_ID_A, I2C_MEMADD_SIZE_8BIT, id, 3, HAL_MAX_DELAY);
    int id_value = (id[0] << 16) | (id[1] << 8) | id[2]; // 将读取的ID转换为整数
    if (id_value != HMC5883_ID_VALUE)
    {
        // ID不匹配，初始化失败
        HAL_UART_Transmit(&huart2, (uint8_t *)"HMC5883 Not Found\r\n", 20, HAL_MAX_DELAY);
        while (1)
        {
            HAL_Delay(1000); // 无限循环等待
            HAL_I2C_Mem_Read(hi2c, HMC5883_ADDRESS << 1, HMC5883_ID_A, I2C_MEMADD_SIZE_8BIT, id, 3, HAL_MAX_DELAY);
            HAL_UART_Transmit(&huart2, (uint8_t *)"HMC5883 Not Found\r\n", 20, HAL_MAX_DELAY);
            HAL_UART_Transmit(&huart2, id, 3, HAL_MAX_DELAY); // 打印读取的ID
        }
    }
    else
    {
        // ID匹配，初始化成功
        HAL_UART_Transmit(&huart2, (uint8_t *)"HMC5883 Found!\r\n", 16, HAL_MAX_DELAY);
    }
    uint8_t mode = HMC5883_MODE_CONTINUOUS; // Continuous mode
    HAL_I2C_Mem_Write(hi2c, HMC5883_ADDRESS << 1, HMC5883_MODE, I2C_MEMADD_SIZE_8BIT, &mode, 1, HAL_MAX_DELAY);
    HAL_Delay(10); // 等待配置完成
    HAL_UART_Transmit(&huart2, (uint8_t *)"HMC5883 Initialized\r\n", 22, HAL_MAX_DELAY);
}
/*读取HMC5883数据函数*/
void HMC5883_ReadData(I2C_HandleTypeDef *hi2c, int *data)
{
    uint8_t buffer[6]; // 存储读取数据的数组
    HAL_I2C_Mem_Read(hi2c, HMC5883_ADDRESS << 1, HMC5883_DATA_X_MSB, I2C_MEMADD_SIZE_8BIT, buffer, 6, HAL_MAX_DELAY);

    // 将读取的数据转换为整数
    data[0] = (int16_t)((buffer[0] << 8) | buffer[1]); // X轴数据
    data[1] = (int16_t)((buffer[4] << 8) | buffer[5]); // Y轴数据
    data[2] = (int16_t)((buffer[2] << 8) | buffer[3]); // Z轴数据

    // 打印读取的数据
    char msg[50];
    snprintf(msg, sizeof(msg), "X: %d, Y: %d, Z: %d\r\n", data[0], data[1], data[2]);
    HAL_UART_Transmit(&huart2, (uint8_t *)msg, strlen(msg), HAL_MAX_DELAY);
}
